<?php

namespace Cms;

use Cms\Article\Reply;
use Cms\Article\Tag;

class Article extends \Model {
    
    use \UserModel;
    use \State;

    static public $table = 'cms_article';
    protected $_fillable = array(
        'id' => 'int',
        'column_id' => 'int',
        'state' => 'int',
        'sort' => 'int',
        'top' => 'int',
        'hot' => 'int',
        'type' => 'str',
        'title' => 'str',
        'keywords' => 'str',
        'description' => 'str',
        'thumb' => 'str',
        'content' => 'str',
        'pv' => 'int',
        'redirect' => 'str',
        'jump' => 'int',
        'pushed' => 'int',
        'publish_time' => 'datetime',
        'add_time' => 'datetime',
        'update_time' => 'datetime',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'address' => 'str',
    );
    
    const STATE_ON = 1;
    const STATE_OFF = -1;
    
    protected $_states = [
        self::STATE_ON => '显示',
        self::STATE_OFF => '隐藏',
    ];

    /**
     * 
     * @return Reply
     */
    public function Reply() {
        static $o;
        return isset($o) ? $o : $o = new Reply();
    }

    /**
     * 
     * @return Tag
     */
    public function Tag() {
        static $o;
        return isset($o) ? $o : $o = new Tag();
    }
    
    public function getTypeAssoc($key = null) {
        $arr = array(
            'page' => '普通',
            'image' => '图集',
            'video' => '视频',
            'url' => '链接',
        );
        
        if ($key !== null) {
            if (array_key_exists(strval($key), $arr)) {
                return $arr[strval($key)];
            } else {
                return '';
            }
        } else {
            return $arr;
        }
    }

    public function removeAll($ids) {
        if (!is_array($ids) || count($ids) == 0) {
            return false;
        }
        $where = array('id' => array('in' => $ids));
        return Db()->delete(static::$table, $where);
    }

    public function incPv($id) {
        $where = array('id' => $id);
        $arrSets = 'pv = pv + 1';
        $result = Db()->update(static::$table, $arrSets, $where);
        return $result;
    }

    public function getPreOne($column_id, $id) {
        $where = array(
            'id' => array('<' => $id),
            'column_id' => $column_id,
        );
        $result = Db()->getRow(static::$table)->where($where)->order('id', 'desc')->limit(1)->result();
        if ($result) {
            $this->fillAssoc($result);
        }
        return $result;
    }

    public function getNextOne($column_id, $id) {
        $where = array(
            'id' => array('>' => $id),
            'column_id' => $column_id,
        );
        $result = Db()->getRow(static::$table)->where($where)->order('id')->limit(1)->result();
        if ($result) {
            $this->fillAssoc($result);
        }
        return $result;
    }

    public function countListByColumnIds($column_ids, $filter = []) {
        $where = [
            'state' => 1,
            'column_id' => ['in' => $column_ids],
        ];
        return Db()->count(static::$table)->where($where)->where($filter)->result();
    }

    public function getListByColumnIds($column_ids, $start = null, $length = null, $filter = []) {
        $where = [
            'state' => 1,
            'column_id' => ['in' => $column_ids],
        ];
        $rows = Db()->getAll(static::$table)->where($where)->where($filter)->limit($start, $length)->order('sort desc, publish_time desc, id desc')->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function fillAssoc(&$detail) {
        $detail['reply_count'] = Cms()->Article()->Reply()->countByActicle($detail['id']);
        $detail['description'] = $detail['description'] ? toHtml($detail['description']) : stripTag(htmlspecialchars_decode($detail['content']));

        $tags = Cms()->Article()->Tag()->getListByArticle($detail['id']);

        foreach ($tags as &$tag) {
            $tag = Cms()->Tag()->get($tag['tag_id']);
        }
        unset($tag);

        $detail['tags'] = $tags;
        return $detail;
    }

    public function getMostPvListByColumnId($column_id, $start = null, $length = null) {
        $where = array(
            'state' => 1,
            'column_id' => $column_id
        );
        $rows = Db()->getAll(static::$table)->limit($start, $length)->where($where)->order('pv desc')->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function getListByColumnId($column_id, $start = null, $length = null, $filter = []) {
        $where = array(
            'state' => 1,
            'column_id' => $column_id
        );
        $rows = Db()->getAll(static::$table)->limit($start, $length)->where($where)->where($filter)->order('publish_time desc, id desc')->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function countListByColumnId($column_id, $filter = []) {
        $where = array(
            'state' => 1,
            'column_id' => $column_id
        );
        $result = Db()->count(static::$table)->where($where)->where($filter)->result();
        return $result;
    }

    /**
     * 设置总站首页公告板推荐排序
     */
    public function setTop($id, $sort) {
        $where = array('id' => $id);
        $data = array('top' => $sort);
        return Db()->update(static::$table, $data, $where);
    }

    /**
     * 设置总站首页分版块推荐排序
     */
    public function setHot($id, $sort) {
        $where = array('id' => $id);
        $data = array('hot' => $sort);
        return Db()->update(static::$table, $data, $where);
    }

    /**
     * 总站首页公告板推荐
     */
    public function getTops($length) {
        $where = array(
            'state' => 1,
        );
        $rows = Db()->getAll(static::$table)->limit(0, $length)->order('top desc, publish_time desc, id desc')->where($where)->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    /**
     * 总站首页分版块推荐，总站版块列表页和详情页右侧推荐栏
     */
    public function getHotsByColumnId($column_id, $start = null, $length = null) {
        $where = array(
            'state' => 1,
            'column_id' => $column_id,
        );

        $rows = Db()->getAll(static::$table)->limit($start, $length)->order('hot desc, publish_time desc, id desc')->where($where)->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function getList($start, $length, $filter = array(), $order = array()) {
        $filter['state'] = 1;
        if (!$order) {
            $order = 'sort desc, publish_time desc, id desc';
        }
        $rows = Db()->getAll(static::$table)->where($filter)->order($order)->limit($start, $length)->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function countList($keywords) {
        $keywords = Db()->escape($keywords, false);
        return Db()->getOne(static::$table)->fields('count(*)')
                        ->where(array('state' => 1))
                        ->where("title like '%{$keywords}%' or description like '%{$keywords}%'")
                        ->limit(1)
                        ->result();
    }

    public function searchList($keywords, $offset = null, $length = null) {
        $keywords = Db()->escape($keywords, false);
        $rows = Db()->getAll(static::$table)
                ->where(array('state' => 1))
                ->where("title like '%{$keywords}%' or description like '%{$keywords}%'")
                ->limit($offset, $length)->order("{$this->_id} desc")
                ->result();
        foreach ($rows as &$row) {
            $this->fillAssoc($row);
        }
        unset($row);
        return $rows;
    }

    public function searchIds($keywords) {
        $keywords = Db()->escape($keywords, false);
        return Db()->getCol(static::$table)
                        ->where("title like '%{$keywords}%'")
                        ->order("{$this->_id} desc")
                        ->fields('id')
                        ->result();
    }

    public function getUnpushedIds() {
        $where = array(
            'pushed' => 0,
        );
        return Db()->getCol(static::$table)->fields('id')->where($where)->limit(10)->result();
    }

    public function setPushed($ids) {
        $where = array(
            'id' => array('in' => $ids),
        );
        return Db()->update(static::$table, array('pushed' => 1), $where);
    }
}
